package factory.one.service;

import factory.one.entity.Send;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.List;

/**
 * @author sk.z
 * 2023/8/22
 * 货运
 **/
@Service
public class SendService {

    private final Logger log = LoggerFactory.getLogger(SendService.class);

    private final JdbcTemplate jdbcTemplate;

    public SendService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Integer getNextSequence(Long orderId) {
        List<Send> sendList = listByOrder(orderId);
        if (sendList == null || sendList.isEmpty()) {
            return 1;
        }
        int i = 0;
        for (Send s : sendList) {
            i = Math.max(i, s.getSequence());
        }
        return i + 1;
    }

    public Long add(Send send) {
        PreparedStatementCreator preparedStatementCreator = con -> {
            PreparedStatement statement = con.prepareStatement("insert into SEND(order_id,batch_id,sequence,number,create_user,create_time) values(?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
            statement.setLong(1, send.getOrderId());
            statement.setLong(2, send.getBatchId());
            statement.setInt(3, send.getSequence());
            statement.setInt(4, send.getNumber());
            statement.setString(5, send.getCreateUser());
            statement.setTimestamp(6, new Timestamp(send.getCreateTime().getTime()));
            return statement;
        };
        GeneratedKeyHolder holder = new GeneratedKeyHolder();
        jdbcTemplate.update(preparedStatementCreator, holder);
        return holder.getKey() == null ? null : holder.getKey().longValue();
    }

    public List<Send> listByOrder(Long orderId) {
        return jdbcTemplate.query("select * from SEND where order_id = ? ", new SendRowMapper(), orderId);
    }

    private static class SendRowMapper implements RowMapper<Send> {
        @Override
        public Send mapRow(ResultSet rs, int rowNum) throws SQLException {
            Send send = new Send();
            send.setId(rs.getLong("id"));
            send.setOrderId(rs.getLong("order_id"));
            send.setBatchId(rs.getLong("batch_id"));
            send.setSequence(rs.getInt("sequence"));
            send.setNumber(rs.getInt("number"));
            send.setCreateUser(rs.getString("create_user"));
            send.setCreateTime(rs.getTimestamp("create_time"));
            return send;
        }
    }

}
